'use strict';

const util = require('util');

class Serialize {
    constructor() {
        this.register = {};
        this.baseSerialize = {
            contentTypes: [],
            match: function (options) {
                let contextType = options.headers['content-type'] || options.headers['Content-Type'];
                if (!contextType) return false;
                for (let type of this.contentTypes) {
                    if (contextType.toLowerCase() === type) {
                        return true;
                    }
                }
                return false;
            },
            serialize: (data) => {
                return data.toString();
            }
        }
        this.baseSerialize;
    }

    add(serialize) {
        if (serialize.name) {
            this.register[serialize.name] = Object.assign(this.baseSerialize, serialize);
        }
    }

    serializeData(data, options) {
        for (let name in this.register) {
            let serializer = this.register[name];
            if (serializer.match(options)) {
                return serializer.serialize(data);
            }
        }
        return this.baseSerialize.serialize(data);
    }

}

const DefaultSerializeManager = new Serialize();

DefaultSerializeManager.add({
    name: 'json',
    contentTypes: ['application/json', 'application/json;charset=utf-8'],
    serialize: (data) => {
        return JSON.stringify(data)
    }
})

module.exports = DefaultSerializeManager
